﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StructureMap;
using Yala.Client.Web.MVC.Authentication.DotNetOpenAuth;

namespace Yala.Client.Web.MVC.Authentication
{
    public class ObjectFactoryBootstrapper : IBootstrapper
    {
        private static bool _hasStarted;

        public void BootstrapStructureMap()
        {
            ObjectFactory.Initialize(x =>
            {
                x.PullConfigurationFromAppConfig = false;
                x.UseDefaultStructureMapConfigFile = false;

                x.AddRegistry(new AuthenticationRegistry());
                
            });

            ObjectFactory.Configure(x => x.Scan(scanner =>
                                                    {
                                                        scanner.SingleImplementationsOfInterface();
                                                        scanner.AssemblyContainingType<DotNetOpenAuthManager>(); // Yala.Core
                                                    }));
        }

        /// <summary>
        /// Starting the container is a relatively expensive activity, so we only want 
        /// to call ObjectFactory.Initialize(). The call to ObjectFactory.ResetDefaults() 
        /// simply clears default services injected into the container after initialization.  
        /// This is mostly used to clear out any mock or stub objects introduced in a unit 
        /// test after the unit test is over.
        /// </summary>
        public static void Restart()
        {
            if (_hasStarted)
            {
                ObjectFactory.ResetDefaults();
            }
            else
            {
                Bootstrap();
                _hasStarted = true;
            }
        }

        public static void Bootstrap()
        {
            new ObjectFactoryBootstrapper().BootstrapStructureMap();
        }
    }
}
